const sql = require("../../mysql");
const md5 = require("md5");

module.exports = async ctx => {
  try {
    if (ctx.request.userRole !== "admin") {
      ctx.body = {
        code: -1,
        msg: "没有权限"
      };
      return;
    }
    let { uname } = ctx.request.body;
    if (!uname) {
      ctx.body = {
        code: -1,
        msg: "请输入用户名"
      };
    }

    await sql.User.create({
      uname: uname.trim(),
      password: md5(md5("123456")),
      role: "user"
    });

    ctx.body = {
      code: 0,
      msg: "注册成功"
    };
  } catch (error) {
    console.log(error);
    ctx.response.status = 200;

    ctx.body = {
      code: -1,
      msg: error.errors ? error : error.errors[0].message
    };
  }
};
